2164. Julius Caesar Cyfer

 

Julius Caesar used his own method of text encryption. Each letter was replaced by the letter located k positions forward in the alphabet, with the alphabet treated as cyclic.

Given the encrypted text, restore the original message.

 

Input. The first line contains the encrypted message, consisting of no more than 255 uppercase Latin letters.

The second line contains an integer k (1 ≤ k ≤ 10).

 

Output. Print the decrypted text.

 

Sample input

Sample output

XPSE

1

WORD

 

 

SOLUTION

strings

 

Algorithm analysis

To decrypt the text, each letter should be shifted k positions backward in a cyclic manner. We number the letters from 0 (‘A’) to 25 (‘Z’).

Let s[i] be the current letter of the cipher. Its position in the alphabet is computed as s[i] – ‘A’. To perform the backward shift while considering the cyclic nature of the alphabet (where ‘Z’ comes before ‘A’), subtract k and take the result modulo 26. Then, add ‘A’ to obtain the ASCII code of the decrypted letter.

Thus, the decryption operation is as follows:

s[i] = (s[i] – ‘A’ – k + 26) % 26 + ‘A’

 

Algorithm implementation

Store the input string in the character array s.

 

char s[1000];

 

Read the input data.

 

gets(s); scanf("%d", &k);

 

Transform the characters of the string according to the decryption rule.

 

for (i = 0; i < strlen(s); i++)

  s[i] = (((s[i] - 'A') + 26 - k) % 26) + 'A';

 

Print the decrypted text.

 

puts(s);

 

Algorithm implementation – STL

Read the input data.

 

cin >> s >> k;

 

Transform the characters of the string according to the decryption rule.

 

for (i = 0; i < s.size(); i++)

  s[i] = (((s[i] - 'A') + 26 - k) % 26) + 'A';

 

Print the decrypted text.

 

cout << s << endl;

 

Python implementation

Read the input data.

 

s = input()

k = int(input())

 

Transform the characters of the string according to the decryption rule.

 

s = ''.join(chr(((ord(c) - ord('A') - k + 26) % 26) + ord('A'))

                for c in s)

 

Print the decrypted text.

 

print(s)